<template>
  <div id="globalHeader">
    <!-- 顶部菜单布局  -->
    <!-- 关闭自动换行-->
    <a-row :wrap="false">
      <a-col flex="200px">
        <RouterLink to="/">
          <div class="title-bar">
            <img class="logo" src="../assets/xp.png" alt="logo" />
            <div class="title">小胖协同云图库</div>
          </div>
        </RouterLink>
      </a-col>
      <a-col flex="auto">
        <a-menu
          v-model:selectedKeys="current"
          mode="horizontal"
          :items="items"
          @click="doMenuClick"
        />
      </a-col>
      <a-col flex="150px">
        <div class="user-login-status">
          <div v-if="loginUserStore.loginUser.id">
            <a-dropdown>
              <a-space>
                <a-avatar :src="loginUserStore.loginUser.userAvatar" />
                {{ loginUserStore.loginUser.realName ?? '无名' }}
              </a-space>
              <template #overlay>
                <a-menu>
                  <a-menu-item @click="doLogout">
                    <LogoutOutlined />
                    退出登录
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </div>
          <div v-else>
            <a-button type="primary" href="/user/login">登录</a-button>
          </div>
        </div>
      </a-col>
    </a-row>
  </div>
</template>
<script lang="ts" setup>
import { computed, h, ref } from 'vue'
import { HomeOutlined, GithubOutlined, LogoutOutlined } from '@ant-design/icons-vue'
import { MenuProps, message } from 'ant-design-vue'
import router, { routesOptions } from '@/router'
import { useLoginUserStore } from '@/stores/user'
import { userLogoutUsingPost } from '@/api/userController'
import checkAccess from '@/access/access'

const loginUserStore = useLoginUserStore()

const current = ref<string[]>([])

// 监听路由变化，更新当前选中菜单
router.afterEach((to, from, next) => {
  current.value = [to.path]
})

/**
 * 根据路由组织菜单
 * 过滤掉隐藏项和权限不足的项目
 * @param routes
 */
const setMenuItems = (routes: any) => {
  const originItems = []
  for (let i = 0; i < routes.length; i++) {
    const route = routes[i]
    // 如果路由有meta.hidden属性，则跳过
    if (route?.meta?.hidden) continue
    if (!checkAccess(loginUserStore.loginUser, route?.meta?.access)) continue
    originItems.push({
      key: route.path,
      icon: route?.meta?.icon,
      label: route.name,
      title: route.name,
    })
  }
  originItems.push({
    key: 'others',
    icon: () => h(GithubOutlined),
    label: h('a', { href: 'https://gitee.com/s1eep1022/pic-frontend', target: '_blank' }, 'Gitee'),
    title: 'Gitee',
  })
  return originItems
}

// 过滤菜单项
const filterMenus = (menus = [] as MenuProps['items']) => {
  return menus?.filter((menu) => {
    if (menu?.key?.startsWith('/admin')) {
      const loginUser = loginUserStore.loginUser
      if (!loginUser || loginUser.userRole !== 'admin') {
        return false
      }
    }
    return true
  })
}

// 展示在菜单的路由数组
const items = computed(() => setMenuItems(routesOptions))

const doMenuClick = ({ key }: { key: string }) => {
  router.push({
    path: key,
  })
}

// 退出登录
const doLogout = async () => {
  const res = await userLogoutUsingPost()
  if (res.data.code === 0) {
    loginUserStore.setLoginUser({
      userName: '未登录',
    })
    message.success('登出成功')
    await router.push('/user/login')
  } else {
    message.error('退出登录失败，' + res.data.message)
  }
}
</script>

<style scoped>
.title-bar {
  display: flex;
  align-items: center;
}

.title {
  color: black;
  font-size: 18px;
  margin-left: 16px;
}

.logo {
  height: 48px;
}
</style>
